package org.lzy.shop.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.response.CouponResponse
import org.lzy.shop.viewmodel.repository.CouponRepository
import org.lzy.shop.viewmodel.repository.lmpl.CouponRepositoryImpl

/**
 * 优惠劵的VM层
 */
class CouponModel: BaseViewModel() {

    private val couponRepository: CouponRepository=CouponRepositoryImpl()

    // 可用优惠券数据
    val myData by lazy { MutableLiveData<CouponResponse?>() }

    // 我的优惠券数据
    val myCouponData by lazy { MutableLiveData<CouponResponse?>() }

    // 领取优惠券结果
    val receiveResultData by lazy { MutableLiveData<String?>() }

    // 领取优惠券错误
    val receiveErrorData by lazy { MutableLiveData<String?>() }


    /**
     * 获取我的优惠券列表
     */
    fun getMyCoupon(page: Int): LiveData<CouponResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = couponRepository.getMyCoupons(page, 10)
                myCouponData.value = response
            } catch (e: Exception) {
                e.printStackTrace()
                // 错误处理
            }
        }
        return myCouponData
    }

    /**
     * 领取优惠券
     */
    fun receiveCoupon(couponId: Int?) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                if (couponId == null) {
                    receiveErrorData.value = "优惠券ID不能为空"
                    return@launch
                }
                val response = couponRepository.receiveCoupon(couponId)
                receiveResultData.value = response
            } catch (e: Exception) {
                e.printStackTrace()
                // 异常处理，从异常中提取错误信息
                val exception = ExceptionHandler.handleException(e)
                receiveErrorData.value = exception.errMsg ?: e.message
            }
        }
    }
}